package com.hzit.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.content.dto.ContentQuery;
import com.hzit.content.entity.Content;
import com.hzit.content.mapper.ContentMapper;
import com.hzit.content.service.ContentService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements ContentService {
    
    @Override
    public String uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        
        try {
            String uploadPath = "/upload/"; // 配置实际的上传路径
            File dest = new File(uploadPath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return "/upload/" + fileName; // 返回访问URL
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
    
    @Override
    public Page<Content> queryPage(ContentQuery query) {
        LambdaQueryWrapper<Content> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(query.getTitle()), Content::getTitle, query.getTitle());
        wrapper.orderByDesc(Content::getCreated);
        
        return page(new Page<>(query.getPageNum(), query.getPageSize()), wrapper);
    }
} 